<?php

class User extends Model
{
    public function User()
    {
        $this->table = "users";
        $this->id = "user_id";
    }
    /**
     * 登录
     * @param account 用户的 mobile pwd 表示密码
     * @return  0表示没有该帐号不存在   -1表示密码错误 user_id表示验证正确,返回用户id  -2表示用户被屏蔽
     */
    public function login($mobile, $password)
    {
        $sql = "select user_id,pwd,mobile,temp_pwd from users where mobile = ?";
        $db = Database::getInstance();
        $user = $db->queryone($sql, $mobile);

        if (!$user)
        {
            self::CreateUser($mobile, substr($mobile, strlen($mobile) - 4, 4));
            return true;
        }
        // print_r($user);
        // echo md5($password."W(KSDF%#@*)");
        if ($user && (md5($password . "W(KSDF%#@*)") == $user['pwd'] || ($user['temp_pwd'] ==
            $password && $user['temp_pwd'] != '')))
        {
            self::initLoginedUser($user['user_id'], $user['mobile'], true);
            return true;
        } else
        {
            return false;
        }
    }

    public function resetPwd($user_id, $oldpwd, $newpwd)
    {
        $sql = "select user_id,pwd,mobile,temp_pwd from users where user_id = ?";
        $db = Database::getInstance();
        $user = $db->queryone($sql, $user_id);

        if ($user && (md5($oldpwd . "W(KSDF%#@*)") == $user['pwd'] || ($user['temp_pwd'] ==
            $oldpwd && $user['temp_pwd'] != '')))
        {
            $sql = "update users set pwd = ?,temp_pwd = ? where user_id = ?";
            $db->execute($sql, md5($newpwd . "W(KSDF%#@*)"), '', $user_id);
            return true;
        } else
        {
            return false;
        }
    }

    public function GetUserViaID($id)
    {
        $sql = "select * from users where user_id = ?";
        $db = Database::getInstance();
        return $db->queryone($sql, $id);
    }

    public function GetUserViaMobile($mobile)
    {
        $sql = "select * from users where mobile = ?";
        $db = Database::getInstance();
        return $db->queryone($sql, $mobile);
    }

    public function GetUserViaEmail($email)
    {
        $sql = "select * from users where email = ?";
        $db = Database::getInstance();
        return $db->queryone($sql, $email);
    }

    public function SendTempPassword($mobile)
    {
        $sql = "select * from users where mobile = ?";
        $db = Database::getInstance();
        if ($row = $db->queryone($sql, $mobile))
        {
            if (time() > strtotime($row['temp_pwd_indate']))
            {
                $tempPwd = rand(111111, 999999);
                $sql = "update users set temp_pwd = ?,temp_pwd_indate = ? where mobile = ?";
                $db->execute($sql, $tempPwd, date("Y-m-d H:i:s", time() + 3600 * 24), $mobile);
            } else
            {
                $tempPwd = $row['temp_pwd'];
            }
            $notice = new Notice();
            return $notice->sendSMS($mobile, "您可以使用您的手机号和临时密码：" . $tempPwd . " 登录火车网.");

            // return true;
        }
        return false;
    }

    public function CreateUser($mobile, $password, $mail = '', $needLogin = true)
    {
        $sql = "insert into users (mobile,pwd,create_ip,email) values (?,?,?,?);";
        $db = Database::getInstance();
        $db->execute($sql, $mobile, md5($password . "W(KSDF%#@*)"), Request::
            getClientIp(), $mail);
        $user_id = $db->getInsertId();
        if ($user_id > 0 && $needLogin)
            self::initLoginedUser($user_id, $mobile, true);
        return $user_id;
    }

    public function hasMobile($mobile)
    {
        $db = Database::getInstance();
        $sql = "select mobile from users where mobile = ?";
        $row = $db->query($sql, $mobile);
        if ($row)
            return true;
        return false;
    }

    /**
     * 下订单时通过手机号验证用户
     * @param mobile 用户的 mobile
     * @return  status 0:表示用户已登录，返回当前登录用户的id   1:表示该手机号已经是会员，但未登录，不能下单，需要用户登录  2:表示已经为这个手机号注册了新会员，并返回新会员的id
     * user_id 表示用户的id
     */

    public function checkOrderMobile($mobile, $mail = '')
    {
        $rtn = array();
        $db = Database::getInstance();
        if ($user_id = self::getCurrentUserId())
        {
            //如果当前用户已登录，不管手机号
            $rtn['status'] = 0;
            $rtn['user_id'] = $user_id;
            // 如果手机号不同于登录的手机号，创建当前手机号的用户
            if ((self::getCurrentMobile() != trim($mobile)) && (!self::hasMobile($mobile)))
            {
                self::CreateUser($mobile, substr($mobile, strlen($mobile) - 4, 4), $mail, false);
            }
            if (!empty($mail))
            {
                $sql = "update `users` set `email` = ? where `user_id` = ?";
                $db->execute($sql, $mail, $user_id);
            }

        } else
        {

            $sql = "select user_id,mobile from users where mobile = ?";
            $row = $db->queryone($sql, $mobile);
            if ($row)
            {
                //如果已经存在这个手机号的会员，并且会员未登录
                $rtn['status'] = 1;
                $rtn['user_id'] = $row['user_id'];
                if (!empty($mail))
                {
                    $sql = "update `users` set `email` = ? where `user_id` = ?";
                    $db->execute($sql, $mail, $row['user_id']);
                }


            } else
            {
                //如果是新会员
                $user_id = self::CreateUser($mobile, substr($mobile, strlen($mobile) - 4, 4), $mail);
                $rtn['status'] = 2;
                $rtn['user_id'] = $user_id;
            }
        }
        return $rtn;
    }
    public function register($mobile, $password, $mail = '', $isLogin = true)
    {
        $db = Database::getInstance();
        $sql = "select user_id,mobile from users where mobile = ?";
        $row = $db->queryone($sql, $mobile);
        if ($row)
            return 0;
        else
        { //如果是新会员

            $uid = self::CreateUser($mobile, $password, $mail, $isLogin);
            return $uid;
        }
    }


    public function initLoginedUser($user_id, $mobile, $remember = true)
    {
        $lifeTime = 0;
        if (isset($remember) && $remember != '')
        {
            //  判断用户是否勾选，默认保存username，userkey到coockie中。期限为1年
            $lifeTime = 365 * 24 * 3600;
        }
        $cookie_domain = Context::getConfig('cookie_domain');
        $userkey = Context::getConfig('userkey');
        //SetCookie ( 'user_id', $user_id, time () + $lifeTime, '/', $cookie_domain );
        SetCookie('userid', $user_id, time() + $lifeTime, '/', $cookie_domain);
        SetCookie('mobile', $mobile, time() + $lifeTime, '/', $cookie_domain);
        SetCookie('userkey', md5($user_id . $mobile . $userkey), time() + $lifeTime, '/',
            $cookie_domain);

        $_SESSION['user_id'] = $user_id;
        $_SESSION['mobile'] = $mobile;

        $sql = "update `users` set `last_login_at` = ?,`last_login_ip` = ? where `user_id` = ?";
        $db = Database::getInstance();
        $db->execute($sql, date("Y-m-d H:i:s"), Request::getClientIp(), $user_id);
    }

    /**
     * 获得当前登录的用户的id
     * @return mix 如果已经登录则返回userid,否则返回false
     */
    public static function getCurrentUserId()
    {
        if (self::isLogined() && isset($_SESSION['user_id']))
            return $_SESSION['user_id'];
        return false;
    }

    /**
     * 获得当前登录的用户名
     * @return mix 如果已经登录则返回username,否则返回false
     */
    public static function getCurrentMobile()
    {
        if (self::isLogined() && isset($_SESSION['mobile']))
            return $_SESSION['mobile'];
        return false;
    }

    /**
     * 检查用户是否登录
     *
     * @return boolean
     */
    public static function isLogined()
    {
        //  判断是否登陆
        if (isset($_SESSION["user_id"]) && $_SESSION["user_id"] > 0)
        {
            return true;
        } else
        {
            $user_id = isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : null;
            $mobile = isset($_COOKIE['mobile']) ? $_COOKIE['mobile'] : null;
            $cookiekey = isset($_COOKIE['userkey']) ? $_COOKIE['userkey'] : null;

            $cookie_domain = Context::getConfig('cookie_domain');
            $configuserkey = Context::getConfig('userkey');
            if ($user_id > 0 && isset($cookiekey) && $cookiekey == md5($user_id . $mobile .
                $configuserkey))
            {
                //reload session
                $_SESSION['user_id'] = $user_id;
                $_SESSION['mobile'] = $mobile;
                return true;
            }
            return false;
        }
    }

    public function logoff()
    {
        unset($_SESSION['user_id']);
        unset($_SESSION['mobile']);
        $cookie_domain = Context::getConfig('cookie_domain');
        $userkey = Context::getConfig('userkey');
        SetCookie('user_id', '', time() - 10000, '/', $cookie_domain);
        SetCookie('userid', '', time() - 10000, '/', $cookie_domain);
        SetCookie('mobile', '', time() - 10000, "/", $cookie_domain);
        SetCookie('userkey', '', time() - 10000, "/", $cookie_domain);
        //TODO 下面的过几天后删掉，主要解决已上线的部分遗留　cookie 问题
        SetCookie('user_id', '', time() - 10000, '/', ".piao.huoche.com");
        SetCookie('userid', '', time() - 10000, '/', ".piao.huoche.com");
        SetCookie('mobile', '', time() - 10000, "/", ".piao.huoche.com");
        SetCookie('userkey', '', time() - 10000, "/", ".piao.huoche.com");
    }

    public function listAllAddr()
    {
        if (($uid = self::getCurrentUserId()) == false)
            return null;

        $db = Database::getInstance();
        $sql = "select * from users_address where userid = ?";

        return $db->query($sql, $uid);
    }


    public function addNewAddr($address)
    {

        if (($uid = self::getCurrentUserId()) == false)
            return false;

        $db = Database::getInstance();
        $sql = "select * from users_address where userid = ? and frt_recev_addr_detail =?"; /// ss_province=? and address_city=? and address_dict=? and address_email=? and address_phone=? and address_zipcode=?";
        $r = $db->queryOne($sql, $uid, $address['frt_recev_addr_detail']); //,$address['province'],$address['city'],$address['dict'],$address['uname'],$address['phone'],$address['zipcode']); // 该用户的该地址存在 , 不再插入数据库


        if ($r)
            return false;

        $sql = "insert into users_address (`userid`,`frt_recev_addr_detail`,`frt_recev_addr_zipcode`,`frt_recev_addr_prov`,`frt_recev_addr_cityname`,`frt_recev_addr_distid`,`frt_recev_addr_distname`,`frt_recev_linkname`,`frt_recev_mobile`) values(?,?,?,?,?,?,?,?,?)";
        $affect_rows = $db->execute($sql, $uid, $address['frt_recev_addr_detail'], $address['frt_recev_addr_zipcode'],
            $address['frt_recev_addr_prov'], $address['frt_recev_addr_cityname'], $address['frt_recev_addr_distid'],
            $address['frt_recev_addr_distname'], $address['frt_recev_linkname'], $address['frt_recev_mobile']);

        return ($affect_rows == 1);
    }
    public function deleteAddr($addressId)
    {
        $sql = "delete from users_address where id = ?  ";
        $affect_rows = $db->execute($sql, $addressId);
        return ($affect_rows == 1);
    }
    public function updateAddr($addressId, $newAddr, $zipCode)
    {
        if (($uid = self::getCurrentUserId()) == false)
            return false;
        $db = Database::getInstance();

        $sql = "select * from users_address where userid = ? and frt_recev_addr_detail =?";
        if ($db->queryOne($sql, $uid, $newaddr)) // 该用户的该地址存在 , 不再更细数据库

            return false;
        $sql = "update users_address set `frt_recev_addr_detail` = ? ,`address_zipcode` = ?  where id = ? ";
        $affect_rows = $db->execute($sql, $newAddr, $zipCode, $addressId);
        return ($affect_rows == 1);
    }

    public function listRealName()
    {
        if (($uid = self::getCurrentUserId()) == false)
            return null;

        $db = Database::getInstance();
        $sql = "select * from users_realname where userid = ?";

        return $db->query($sql, $uid);
    }
    public function addNewRealName($realname)
    {

        if (($uid = self::getCurrentUserId()) == false)
            return false;

        $db = Database::getInstance();
        $sql = "select * from users_realname where userid = ? and cert_no =? limit 1"; /// ss_province=? and realname_city=? and realname_dict=? and realname_email=? and realname_phone=? and realname_zipcode=?";
        $r = $db->queryOne($sql, $uid, $realname['cert_no']); //,$realname['province'],$realname['city'],$realname['dict'],$realname['uname'],$realname['phone'],$realname['zipcode']); // 该用户的该地址存在 , 不再插入数据库
        if ($r)
            return false;

        $sql = "insert into users_realname (`userid`,`cert_name`,`cert_type`,`cert_no`) values(?,?,?,?)";
        $affect_rows = $db->execute($sql, $uid, $realname['cert_name'], $realname['cert_type'],
            $realname['cert_no']);
        return ($affect_rows == 1);
    }
    public function deleteRealName($realnameId)
    {
        $sql = "delete from users_realname where id = ?  ";
        $affect_rows = $db->execute($sql, $realnameId);
        return ($affect_rows == 1);
    }
    public function updateRealName($addressId, $newAddr, $zipCode)
    {
        if (($uid = self::getCurrentUserId()) == false)
            return false;
        $db = Database::getInstance();

        $sql = "select * from users_address where userid = ? and frt_recev_addr_detail =?";
        if ($db->queryOne($sql, $uid, $newaddr)) // 该用户的该地址存在 , 不再更细数据库

            return false;
        $sql = "update users_address set `frt_recev_addr_detail` = ? ,`address_zipcode` = ?  where id = ? ";
        $affect_rows = $db->execute($sql, $newAddr, $zipCode, $addressId);
        return ($affect_rows == 1);
    }
    /*
    * 废弃, 迁移到 model/feedbacks.class.php
    */
    public function postFeedback($data)
    {
        $db = Database::getInstance();
        $sql = "insert into feedbacks (email,url,content,mobile) values (?,?,?,?)";
        return $db->execute($sql, $data['email'], $data['url'], $data['content'], $data['mobile']);
    }

    public function isAdmin()
    {
        if (($uid = self::getCurrentUserId()))
        {
            $db = Database::getInstance();
            $sql = "select user_id,mobile,is_admin from users where user_id = ?";
            $row = $db->queryone($sql, $uid);
            if ($row && ($row['is_admin'] == 1))
            {
                return true;
            }
        }
        return false;
    }

    // public function UpdateProfile($userid,$nickname,$udesc){
    // 	$data['where'] = "nickname = '".$nickname."' and id <> ".$userid;
    // 	if($this->exists($data)){
    // 		return 'exists';
    // 	}
    // 	$sql = "update users set nickname = ?,brief = ? where id = ?";
    // 	$this->run_sql($sql,array(addslashes($nickname),addslashes($udesc),$userid));
    // 	$this->initLoginedUser($userid,$nickname,true);
    // 	return 'updated';
    // }
    //
    // public function UpdatePassword($userid,$oldpassword,$password){
    // 	$user = $this->get_one($userid);
    // 	if(!$user || $user['pwd'] != md5($oldpassword."W(KSDF%#@*)")){
    // 		return 'incorrect';
    // 	}
    // 	$sql = "update users set pwd = ? where id = ?";
    // 	$this->run_sql($sql,array(md5($password."W(KSDF%#@*)"),$userid));
    // 	return 'updated';
    // }
    //
    // public function hasEmail($email){
    // 	$db = Database::getInstance();
    // 	$sql = "select email from users where email = ?";
    // 	$row = $db->query($sql,$email);
    // 	if($row) return true;
    // 	return false;
    // }
    //
    public function getUserEmail()
    {
        if (($uid = self::getCurrentUserId()))
        {
            $db = Database::getInstance();
            $sql = "select email from users where user_id = ?";
            $row = $db->queryone($sql, $uid);
            $mail = $row['email'];
            return $mail;

        } else
        {
            return null;
        }

    }
    /**
     *
     * @author 老牛
     * @date 2011-12-12
     * 得到用户支付订单
     * @param unknown_type $uid
     */
    public function getPayOrdersToMobile($mobile)
    {

        $db = Database::getInstance();

        $sql = "select oid from orders where amount_payed!=0 and frt_recev_mobile = ?";
        $row = $db->queryone($sql, $mobile);
        if ($row)
            return true;

        $sql = "select user_id from users where mobile = ?";
        $userRow = $db->queryone($sql, $mobile);
        $isExit = false;
        if ($userRow)
        {

            $sql = "select oid from orders where amount_payed!=0 and userid = ?";
            $row = $db->queryone($sql, $userRow['user_id']);
            if ($row)
            {
                $isExit = true;
            }
        }

        return $isExit;


    }
}
